﻿#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define SERVER_IP "127.0.0.1"
#define PORT 9999
#define BUFFER_SIZE 1024
#define SOCKET_ERROR -1
void Print(const std::string &msg)
{
  std::cout << msg << std::endl;
}
void Error(const std::string &msg);
int main()
{
  // step01 创建客户端socket
  int sock_clnt;
  if ((sock_clnt = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    Error("socket() error!");

  // step02 连接服务端
  sockaddr_in serverAddr{};
  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(PORT);
  serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
  if (connect(sock_clnt, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1)
  {
    close(sock_clnt);
    Error("connect() error!");
  }

  // step03 读取文件数据
  std::ifstream inputFile;
  inputFile.open("../../TCP_IP_Network_Program_SY_Yi.pdf", std::ios::binary);
  if (!inputFile.is_open())
  {
    close(sock_clnt);
    Error("Failed to open file!");
  }
  char buffer[BUFFER_SIZE];
  size_t total = 0;
  size_t bytesRead = 0;
  while (inputFile.read(buffer, BUFFER_SIZE))
  {
    bytesRead = inputFile.gcount();
    total += bytesRead;
    send(sock_clnt, buffer, bytesRead, 0);
  }

  std::cout << "total size:" << total << std::endl;
  inputFile.close();
  // step04 关闭连接
  shutdown(sock_clnt, SHUT_WR);
  char response[BUFFER_SIZE];
  recv(sock_clnt, response, sizeof(response), 0);
  std::cout << response << std::endl;
  close(sock_clnt);
  return 0;
}
void Error(const std::string &msg)
{
  std::cout << msg << std::endl;
  exit(-1);
}